<template>
  <div class="table-column-component">
    <!-- v-tadaptive:tabHeight -->
    <el-table
      ref="tableLayout"
      :height="tabHeight"
      :data="listData"
      @sort-change="sortChange"
      :span-method="objectSpanMethod"
      v-loading="listLoading"
      @row-click="rowClick"
      @row-dblclick="dblclick"
      @selection-change="handleSelectionChange"
      :show-summary="showSummary"
      :summary-method="sumaryMethod"
      element-loading-text="拼命加载中..."
      fit
      highlight-current-row
      stripe
      border
    >
      <el-table-column
        type="selection"
        align="center"
        width="50"
        fixed="left"
        :selectable="selected"
        v-if="isShowSelector"
      >
      </el-table-column>
      <el-table-column
        label="序号"
        width="60"
        align="center"
        fixed="left"
        v-if="isShowSerial"
      >
        <template slot-scope="scope">
          {{
            scope.$index + 1 > 9 ? scope.$index + 1 : '0' + (scope.$index + 1)
          }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in showTableColumn"
        :key="item.label"
        :label="item.label"
        :prop="item.value"
        :min-width="item.width"
        :align="item.align"
        :show-overflow-tooltip="!item.overflow"
        :sortable="sortFileds.includes(item.value) ? 'custom' : false"
      >
        <template slot-scope="{ row, column, $index }">
          <div v-if="item.isFile">
            <el-link
              type="primary"
              v-if="item.preview"
              class="link"
              @click="item.preview(row)"
              >预览</el-link
            >
            <el-link
              type="primary"
              v-if="item.download"
              class="link"
              :href="item.download(row)"
              target="_blank"
              >下载</el-link
            >
          </div>
          <div v-else-if="item.slotName">
            <slot
              :name="item.slotName"
              :row="row"
              :column="column"
              :index="$index"
            ></slot>
          </div>
          <span v-else>{{ row[item.renameField || item.value] || '/' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        :width="operateColWidth"
        v-if="isShowOperate"
      >
        <template slot-scope="{ row }">
          <slot name="operate" :row="row"></slot>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagePagination" v-if="isShowPagination">
      <el-pagination
        background
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
    <custom-table-head
      v-if="isShowCustomColumn"
      :isStoreValue="true"
      :tableName="tableName"
      :columnArr="tableColumn"
      @updateColumn="updateColumn"
    />
  </div>
</template>
<script>
// import { previewDocFile, previewSigningFile } from '@/http/api'
export default {
  name: 'TableLayout',
  props: {
    tableName: {
      type: String //存储的table表名
    },
    tableColumn: {
      //table列所有json数据
      type: Array,
      default: () => []
    },
    tableData: {
      type: Array, //table表数据
      default: () => []
    },
    total: {
      type: Number, //总数
      default: 0
    },
    listLoading: {
      type: Boolean, //加载
      default: true
    },
    pageSize: {
      type: Number, //分页容量
      default: 20
    },
    operateColWidth: {
      type: Number, //操作处理宽度
      default: 114
    },
    isShowCustomColumn: {
      type: Boolean, //是否展示自定义表头
      default: true
    },
    isShowSerial: {
      type: Boolean, //是否展示序号
      default: true
    },
    isShowSelector: {
      type: Boolean, //是否展示多选
      default: false
    },
    isShowOperate: {
      type: Boolean, // 是否显示操作列
      default: true
    },
    isShowPagination: {
      type: Boolean, // 是否显示分页
      default: true
    },
    isLayout: {
      type: Boolean, // 重新渲染table表
      default: false
    },
    objectSpanMethod: {
      type: Function, // 合并单元格方法
      default: () => {}
    },
    sortFileds: {
      type: Array, //排序字段
      default: () => []
    },
    sortChange: {
      type: Function, // 排序方法
      default: () => {}
    },
    selected: {
      type: Function, // 表格多选时可生效，多选框可勾选和不可勾选的处理  默认全部可选
      default: (row, index) => {
        return true
      }
    },
    showSummary: {
      type: Boolean, //是否显示合计
      default: false
    },
    sumaryMethod: {
      type: Function, //合计方法
      default: () => {}
    }
  },
  data () {
    return {
      tabHeight: null,
      showTableColumn: [],
      listData: [],
      previewLoading: false,
      previewSigningLoading: false
    }
  },
  watch: {
    tableColumn: {
      handler (val) {
        this.updateColumn()
      },
      immediate: true
    },
    tableData: {
      handler (val) {
        this.listData = JSON.parse(JSON.stringify(val))
        if (val.length) {
          this.listData.forEach(item => {
            this.showTableColumn.forEach(col => {
              const {
                value = '',
                format,
                renameField,
                isFile,
                preview,
                download
              } = col
              let val = JSON.parse(JSON.stringify(item))
              // 点语法查找值
              if (value.includes('.')) {
                let len = value.split('.').length
                value.split('.').forEach((k, i) => {
                  val = val[k] === null && i != len - 1 ? {} : val[k] //val[k] = null 后续获取属性报错
                })
              } else {
                val = item[value]
              }
              if (format && typeof format === 'function') {
                item[renameField || value] = format.call(this, val, item)
              } else if (isFile && typeof preview === 'function') {
                col.preview = col.preview.bind(this)
              } else if (isFile && typeof download === 'function') {
                col.download = col.download.bind(this)
              } else {
                item[renameField || value] = val
              }
            })
          })
        }
      },
      deep: true
    },
    isLayout () {
      this.$nextTick(_ => {
        this.setMaxHeight() //切换显示隐藏搜索框时重新计算高度
      })
    }
  },
  methods: {
    updateColumn () {
      const columnArr = JSON.parse(localStorage.getItem('columnArr') || '[]')
      const tempData =
        (columnArr.find(item => item.GridName === this.tableName) || {})
          .ColumnInfos || []
      const keys = tempData.map(item => item.value)
      this.showTableColumn =
        (keys.length &&
          this.tableColumn.filter(item => keys.includes(item.value))) ||
        this.tableColumn
      this.$nextTick(this.doLayout)
    },
    handleSelectionChange (val) {
      this.$emit('selectChange', val)
    },
    handleCurrentChange (pageNum) {
      this.$refs.tableLayout.bodyWrapper.scrollTop = 0
      this.$emit('pageChange', pageNum)
      this.$emit('update:listLoading', true)
    },
    rowClick (row) {
      this.$emit('row-click', row)
    },
    dblclick (row) {
      this.$emit('row-dblclick', row)
    },
    doLayout () {
      this.$refs.tableLayout.doLayout()
    },
    // 预览格式
    previewEvent (logicId) {
      if (this.previewLoading) return false
      this.previewLoading = true
      // previewDocFile(logicId, true)
      //   .then(res => {
      //     window.open(res, '_blank')
      //   })
      //   .finally(_ => (this.previewLoading = false))
    },
    // 预览签发表
    previewSignFile (orderId) {
      if (this.previewSigningLoading) return false
      this.previewSigningLoading = true
      // previewSigningFile(orderId)
      //   .then(res => {
      //     let pdf = URL.createObjectURL(new Blob([res]))
      //     pdf = encodeURIComponent(pdf)
      //     window.open('/static/pdf/web/viewer.html?file=' + pdf, 'PDF')
      //   })
      //   .finally(_ => (this.previewSigningLoading = false))
    }
  }
}
</script>
<style lang="less" scoped>
.table-column-component {
  :deep(.el-link) {
    color: #3399ff;

    & + .el-link {
      margin-left: 16px;
    }
  }
  :deep(.el-link.el-link--primary.is-disabled) {
    color: #8aa7ce;
  }
}
.pagePagination {
  // 覆盖默认分页选中样式
  :deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
    background: linear-gradient(90deg, #2268e8 0%, #86b8ff 100%);
    color: #fff;
  }
}
</style>
